package com.netcracker.studies;

import Bank.Account;
import Bank.TransactionFactory;
import Bank.User;
import Beans.AuthorizationBeanInterface;
import Beans.TransactionProcessorBeanInterface;
import DBConnection.DBAPI;
import DBConnection.DBTools;
import org.apache.log4j.Logger;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigInteger;
import java.sql.Date;
import java.util.Calendar;
import java.util.List;


@WebServlet(name = "Transaction")
public class Transaction extends BaseServlet {
    private static final Logger log = Logger.getLogger(User.class);
    protected void handlePostRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(true);
        response.setContentType("text/plain; charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        if ((request.getParameter("to").isEmpty()) || (request.getParameter("sum").isEmpty())){
            response.getWriter().write("Заполните все поля");
            return;
        }

        AuthorizationBeanInterface a = (AuthorizationBeanInterface) session.getAttribute("UserBean");
        Account from = DBAPI.getAccount(DBAPI.getAccountByNumber(request.getParameter("from")));
        Account to = DBAPI.getAccount(DBAPI.getAccountByNumber(request.getParameter("to")));
        if (to != null && from != null) {
            if (from.getNumber() == to.getNumber()) {
                response.getWriter().write("Убедитесь что счета выбраны верно");
                return;
            }

            User initiator = DBAPI.getUser(DBAPI.getObject(new BigInteger(a.getUserId())));
            int sum = new Integer(request.getParameter("sum"));
            if (sum <= 0) {
                response.getWriter().write("Сумма перевода должна быть больше 0");
                return;
            }
            try {
                TransactionProcessorBeanInterface bean = InitialContext.doLookup("java:app/StudentsBankWeb-1.0/TransactionProcessorEJB!Beans.TransactionProcessorBeanInterface");
                bean.addTransaction(DBTools.getNewID(), from, to, initiator, sum, Calendar.getInstance().getTime(),
                        Bank.Transaction.transactionStatus.waiting);
                response.getWriter().write("Перевод отправлен");

            } catch (NamingException e) {
                e.printStackTrace();
            }

        }
    }

    protected void handleGetRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(true);
        AuthorizationBeanInterface a = (AuthorizationBeanInterface) session.getAttribute("UserBean");
        List<Account> accs = DBAPI.getAccountsByUserID(new BigInteger(a.getUserId()));
        if (session.getAttribute("accs") != null)
            session.removeAttribute("accs");
        session.setAttribute("accs",accs);
       // response.getWriter().write("transfer.jsp");
        request.getRequestDispatcher("transfer.jsp").forward(request,response);
    }
}
